package com.ysy.serviceImpl;

import cn.hutool.core.util.NumberUtil;
import com.ysy.entity.UserSearchReq;
import com.ysy.entity.UserSearchResponse;
import com.ysy.entity.es.UserIndex;
import com.ysy.persimmons.common.response.PageResponse;
import com.ysy.persimmons.common.response.Response;
import com.ysy.persimmons.common.util.NumberUtils;
import com.ysy.service.UserSearchService;
import io.jsonwebtoken.lang.Collections;
import jakarta.annotation.Resource;
import org.apache.lucene.search.TotalHits;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.Request;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.FieldSortBuilder;
import org.elasticsearch.search.sort.SortBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;


@Service
public class UserSearchServiceImpl implements UserSearchService {


    private final static Logger log = LoggerFactory.getLogger(UserSearchServiceImpl.class);

    @Resource
    private RestHighLevelClient restHighLevelClient;

    /**
     * 根据关键词去es中查询用户信息
     * @param userSearchReq
     * @return
     */
    @Override
    public PageResponse<UserSearchResponse> getUserInfos(UserSearchReq userSearchReq) {

        if (userSearchReq.getPage()<1){
            userSearchReq.setPage(1);
        }
        String keyword = userSearchReq.getKeyword();
        // 当前页码数
        int currentPage =  (userSearchReq.getPage()-1) * 10;
        // 索引构建
        SearchRequest searchRequest = new SearchRequest(UserIndex.NAME);
        // 查询规则,
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        // 条件
        searchSourceBuilder.query(QueryBuilders.multiMatchQuery(keyword,
                UserIndex.FIELD_USER_NAME,
                UserIndex.FIELD_USER_ACCOUNT_ID));
        // 排序规则
        SortBuilder<?> sortBuilder = new FieldSortBuilder(UserIndex.FIELD_USER_FANS_TOTAL)
                .order(SortOrder.DESC);
        searchSourceBuilder.sort(sortBuilder);

        // 分页
        searchSourceBuilder.from(currentPage);
        searchSourceBuilder.size(10);

        // 高亮设置名称
        HighlightBuilder highlightBuilder = new HighlightBuilder().field(UserIndex.FIELD_USER_NAME)
                .preTags("<strong>").postTags("</strong>");
        searchSourceBuilder.highlighter(highlightBuilder);

        searchRequest.source(searchSourceBuilder);

        // 执行请求
        List<UserSearchResponse> userSearchResList = new ArrayList<>();
        long totalHits = 0L;
        try {
            log.info("query user es req:{} " ,searchRequest.toString());
            SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
            totalHits = searchResponse.getHits().getTotalHits().value;
            SearchHits hits = searchResponse.getHits();
            for (SearchHit hit : hits) {
                Map<String, Object> sourceAsMap = hit.getSourceAsMap();
                UserSearchResponse userSearchResponse = new UserSearchResponse();
                userSearchResponse.setUserId(((Number) sourceAsMap.get(UserIndex.FIELD_USER_ID)).longValue());
                userSearchResponse.setName(sourceAsMap.get(UserIndex.FIELD_USER_NAME).toString());

                Map<String, HighlightField> highlightFields = hit.getHighlightFields();
                if (!Collections.isEmpty(highlightFields) && highlightFields.containsKey(UserIndex.FIELD_USER_NAME)) {
                    userSearchResponse.setHighlightName(highlightFields.get(UserIndex.FIELD_USER_NAME).fragments()[0].string());
                }
                userSearchResponse.setAvatar(sourceAsMap.get(UserIndex.FIELD_USER_AVATAR).toString());
                userSearchResponse.setAccount(sourceAsMap.get(UserIndex.FIELD_USER_ACCOUNT_ID).toString());
                userSearchResponse.setNoteTotal((Integer)sourceAsMap.get(UserIndex.FIELD_USER_NOTE_TOTAL));

                Integer numberSize = (Integer) sourceAsMap.get(UserIndex.FIELD_USER_FANS_TOTAL);
                userSearchResponse.setFansTotal(NumberUtils.formatNumberString(numberSize));

                userSearchResList.add(userSearchResponse);

            }
        }catch (Exception e) {
            log.error("查询用户信息搜索异常：",e);
        }

        return PageResponse.success(userSearchResList,userSearchReq.getPage(),totalHits);
    }
}
